package wiki.kaizen.cloud.security.session.config;

import org.apache.shiro.session.Session;
import org.iherus.shiro.cache.redis.RedisCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import wiki.kaizen.cloud.security.session.support.listener.SessionValidateListener;
import wiki.kaizen.cloud.security.session.util.ISecurityUtil;

import java.io.Serializable;
import java.util.Deque;

@Configuration
public class CommonConfig {


    @Bean
    public SessionValidateListener listener(RedisCache<String, Deque<Serializable>> redisCache){
        return new SessionValidateListener() {
            /*
            * session校验失败清除session时 清除对应缓存
            * */
            @Override
            public void fail(Session session) {
                String key = ISecurityUtil.key(session);
                Deque<Serializable> deque = redisCache.get(key);
                if (deque != null){
                    deque.removeFirstOccurrence(session.getId());
                    if (deque.size()==0){
                        redisCache.remove(key);
                    }
                }

            }

            @Override
            public void success(Session session) {}
        };
    }
}
